/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.supinfo.youfood.service;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.*;
import javax.naming.NamingException;

/**
 *
 * @author Michael
 */
@Stateless
public class MessageService {
    @Resource(mappedName="jms/YouFoodConnectionFactory")
    private ConnectionFactory connectionFactory;
    
    @Resource(mappedName="jms/YouFoodQueue")
    private Queue queueDestination;
    
    public void sendKitchenMessage(String Message) throws NamingException {
        Connection connection = null;
        
        try {
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(queueDestination);
            TextMessage message = session.createTextMessage(Message);
            producer.send(message);
        } catch (JMSException ex) {
            System.out.println(ex.getMessage());
        } finally {
            if(connection != null)
                try {
                connection.close();
            } catch (JMSException ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
    
    public List<String> receiveKitchenMessage(){
        Connection connection = null;
        List<String> res = new ArrayList<String>();
        
        try {
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            MessageConsumer receiver = session.createConsumer(queueDestination);
            connection.start();
            Message message = receiver.receiveNoWait();
            String mess="";
            if(message instanceof TextMessage)
                mess = ((TextMessage)message).getText();
            res.add(mess);
            return res;
        } catch (JMSException ex) { 
            System.out.println(ex.getMessage());
            return null;
        } 
    }
    
    public Enumeration getAllMessages() {
        try {
            Connection connection = null;
            
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            QueueBrowser messages = session.createBrowser(queueDestination);
            Enumeration res = messages.getEnumeration();
            return res;
        } catch (JMSException ex) {
            System.out.println(ex.getMessage());
            return null;
        }
    }
}
